//封装Axios请求
import axios from "axios";
import Cookies from "js-cookie";

interface RequestOptions {
    url: string;
    method: string;
    data?: any;
    headers?: any;
    params?: any;
}

const request = axios.create({
    baseURL: "/api",
    timeout: 5000,
});


const baseRequest = (requestOptions:RequestOptions)=>{
    // 优先从localStorage获取token，然后从Cookies获取
    let token = null;
    if (typeof window !== 'undefined') {
        token = localStorage.getItem('auth') || Cookies.get("auth");
    } else {
        token = Cookies.get("auth");
    }
    
    if (token) {
        let headers = requestOptions.headers || {};
        headers.Authorization = `Bearer ${token}`;
        requestOptions.headers = headers;
    }
    
    return new Promise((resolve,reject)=>{
        request(requestOptions).then(res=>{
            //resolve(res.data);
            handleResponse(res,resolve,reject);
        }).catch(err=>{
            handleError(err,reject);
        })
    })
}

// 处理请求结果
const handleResponse = (response:any,resolve:any,reject:any)=>{
    console.log(response);
    const {data,status} = response;
    if(status === 200){
        resolve(data);
    }else if(status === 401){
        // 401 未授权，清除token
        Cookies.remove("auth");
        localStorage.removeItem("auth");
        window.location.href = "/login";
    }else{
        reject(data);
    }
}
const handleError = (error:any,reject:any)=>{
    console.log(error);
    if(error.status === 401){
        Cookies.remove("auth");
        localStorage.removeItem("auth");
        window.location.href = "/login";
    }else{
        reject(error);
    }
}
export default baseRequest;